package com.csot.ry.util;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import cn.hutool.core.util.StrUtil;
import com.csot.common.core.domain.entity.SysDept;
import com.csot.common.core.domain.entity.SysRole;
import com.csot.common.core.domain.entity.SysUser;
import com.csot.common.utils.DictUtils;
import com.csot.common.utils.SecurityUtils;
import com.csot.common.utils.StringUtils;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

public class UserUtils {

    //  返回city 值：sy
    public static String getCity() {
        SysUser su = SecurityUtils.getLoginUser().getUser();
        SysDept sd = su.getDept();
        String city = null;
        Record r = Db.findFirst("select * from sys_dept where dept_id = ?", sd.getDeptId());
        for (int i = 0; i < 10; i++) {
            city = DictUtils.getDictValue("ip_city", r.getStr("dept_name"));
            if (StrUtil.isNotBlank(city)) {
                break;
            } else {
                r = Db.findFirst("select * from sys_dept where dept_id = ?", r.getLong("parent_id"));
                if (Objects.isNull(r)) {
                    break;
                }
            }
        }
        return city;
    }

    public static boolean isRole(String role) {

        SysUser user = SecurityUtils.getLoginUser().getUser();
        if (SecurityUtils.isAdmin(user.getUserId())) {
            return true;
        }

        List<String> roles = user.getRoles().stream().map(r -> {
            return r.getRoleKey();
        }).collect(Collectors.toList());

        return roles.contains(role);

    }

    /*
     *
     * @return 返回角色in的拼接参数
     */
    public static String getRole() {

        SysUser user = SecurityUtils.getLoginUser().getUser();
        List<SysRole> roles = user.getRoles();
        List<String> roleKeys = roles.stream().map(r -> {
            return "'" + r.getRoleKey() + "'";
        }).collect(Collectors.toList());
        return StringUtils.join(roleKeys, ",");

    }

}
